package com.atguigu.sparkstreaming.commitoffsets

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * Created by Smexy on 2022/8/22
 *
 *
 *    演示把偏移量提交到kakfa的注意事项。
 *
 *
 * Exception in thread "main" java.lang.ClassCastException:
 *    org.apache.spark.streaming.dstream.MappedDStream
 *        cannot be cast to
 *    org.apache.spark.streaming.kafka010.CanCommitOffsets
 *
 *     ds1.asInstanceOf[CanCommitOffsets].commitAsync(ranges)
 *
 *     当前的ds1是MappedDStream，无法强转为 CanCommitOffsets类型。
 *
 *     只能用初始的DS，才是DirectKafkaInputDStream，才能调用 asInstanceOf[CanCommitOffsets].commitAsync(ranges)
 *
 *
 *
 *
 */
object CommitOffsetsToKafkaDemo2 {

  def main(args: Array[String]): Unit = {


    val streamingContext = new StreamingContext("local[*]", "wordcount", Seconds(5))

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> "hadoop102:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "sz220409test",
      "auto.offset.reset" -> "latest",
      //①取消自动提交
      "enable.auto.commit" -> "false"
    )


    val topics = Array("topicD")


    // 初始DS，才是DirectKafkaInputDStream
    val ds: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      streamingContext,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    val ds1: DStream[ConsumerRecord[String, String]] = ds.map(record => record)

    ds.foreachRDD(rdd => {

      //②获取到当前批次的偏移量
      val ranges: Array[OffsetRange] = rdd.asInstanceOf[HasOffsetRanges].offsetRanges

      rdd.foreach(record => println(Thread.currentThread().getName + record.value()))

      //③调用API，把每个分区消费到的utilOffset提交到kafka集群的_comsumer_offsets中
      //ds1.asInstanceOf[CanCommitOffsets].commitAsync(ranges)
      ds.asInstanceOf[CanCommitOffsets].commitAsync(ranges)

    })


    streamingContext.start()

    streamingContext.awaitTermination()

  }

}
